using Microsoft.Data.SqlClient;
using DatabaseBackup.Models;

namespace DatabaseBackup.Services
{
    /// <summary>
    /// SQL Server数据库备份服务
    /// </summary>
    public class SqlServerBackupService : IBackupService<SqlServerDatabaseConfig>
    {
        /// <summary>
        /// 执行SQL Server数据库备份
        /// </summary>
        public async Task<bool> BackupAsync(SqlServerDatabaseConfig config, string backupPath)
        {
            Console.WriteLine($"备份路径: {backupPath}");

            try
            {
                // 确保备份目录存在
                Directory.CreateDirectory(backupPath);

                // 生成备份文件名
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileName = $"{config.DatabaseName}_{timestamp}.bak";
                string filePath = Path.Combine(backupPath, fileName);

                // 构建连接字符串
                string connectionString;
                if (config.UseWindowsAuth)
                {
                    connectionString = $"Server={config.Server};Database=master;Integrated Security=True;";
                }
                else
                {
                    connectionString = $"Server={config.Server};Database=master;User Id={config.Username};Password={config.Password}; TrustServerCertificate={config.TrustServerCertificate};";
                }

                // 构建备份SQL命令
                string backupCommand = $"BACKUP DATABASE [{config.DatabaseName}] TO DISK = '{filePath}' WITH INIT";

                // 执行备份命令
                using (var connection = new SqlConnection(connectionString))
                {
                    await connection.OpenAsync();

                    using (var command = new SqlCommand(backupCommand, connection))
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                }

                Console.WriteLine($"SQL Server备份成功: {filePath}");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"SQL Server备份出错 ({config.DatabaseName}): {ex.Message}");
                return false;
            }
        }
    }
}
